package cn.com.controller.wxController;

import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.com.constant.Code;
import cn.com.util.DataResult;
import cn.com.util.HttpUtil;
import cn.com.util.JsonUtil;
import cn.com.wxUtil.wxConstant;
/**
 * 需要结合支付才能测试,openid,prepay_id.暂时不确定支付能不能 成功,还没有填写
 * @author 84135
 *
 */
@RestController
@RequestMapping("/wx/")
public class SendTemplateMsgController {
	@RequestMapping("sendMessage")
	public String sendMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		DataResult dataResult=new DataResult();
		// 1.获取access_token 成功!
		String urls = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxConstant.APPID
				+ "&secret=" + wxConstant.SECRET;
		URL url = new URL(urls);
		String json = HttpUtil.doGet(url);
		JSONObject jsonObject = JSON.parseObject(json);
		String access_token = (String) jsonObject.get("access_token");
		if(StringUtils.isEmpty(access_token)){
		        dataResult.setData(jsonObject.get("errmsg"));
		        dataResult.setCode(Code.ERRORPARM);
		        dataResult.setMessage("获取失败");
		        return JsonUtil.toJsonString(dataResult);
		}
		
		// 2.
		urls = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+access_token;
		LinkedHashMap<String,Object> map = new LinkedHashMap<>();
		map.put("touser", "");  // 用户的openid
		map.put("template_id",wxConstant.TEMPLATE_ID_PAY);
		map.put("form_id", "");  // 支付的prepay_id
		HashMap<String, String> hashmap = new HashMap<String,String>();
		hashmap.put("abc", "成功");
		map.put("data",hashmap);     // 模板内容,这里值必须是一个map集合,因为最终的json数据必须是"data"={}
		
		String jsonString = JSON.toJSONString(map);
		System.out.println(jsonString);
		String postData = cn.com.wxUtil.HttpUtil.postData(urls, jsonString);
		System.out.println(postData);
		return"成功!";
}}
